export function merge(target) {
    for (let i = 1, j = arguments.length; i < j; i++) {
        let source = arguments[i]
        if (source) {
            for (let prop in source) {
                if (source.hasOwnProperty(prop)) {
                    let value = source[prop]
                    target[prop] = value
                }
            }
        }
    }
    return target
}

export function format(date, fmt) {
    let o = {
        'M+': date.getMonth() + 1,
        'D+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds(),
        'q+': Math.floor((date.getMonth() + 3) / 3),
        'S': date.getMilliseconds()
    }
    if (/(Y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    for (var k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
        }
    }
    return fmt
}
//标准时间转换为时间格式
export function formatter(data) {
    var d = new Date(data);
    var datetime = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
    return datetime
}

export function getQueryString(url, name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = url.substr(url.indexOf('?') + 1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

export function isEmpty(obj) {
    for (var name in obj) {
        return false
    }
    return true
}

export function formatDuration(s) {
    if (s < 60) {
        return s + "秒";
    } else if (s < 60 * 60) {
        return parseInt(s / 60) + "分" + s % 60 + "秒"
    } else if (s < 60 * 60 * 60) {
        var seconds = s % (60 * 60);
        return parseInt(s / 60 / 60) + "小时" + parseInt(seconds / 60) + "分" + seconds % 60 + "秒"
    }
}

export function buildTree(data, valueMap) {
    var hashData = {};
    if (data && data.length > 0) {
        data.map(v => {
            if (!hashData[v.parent_id]) {
                hashData[v.parent_id] = [];
            }
            hashData[v.parent_id].push(v);
        });
    }
    var tree = innerBuildTree(hashData, 0, valueMap, false)
    return tree;
}

function innerBuildTree(hashData, parent_id, valueMap, parent_checked) {
    parent_id = parent_id || 0;
    var tree = [];
    var data = hashData[parent_id];
    if (data && data.length > 0) {
        data.map(v => {
            var checked = valueMap[v.id] ? true : parent_checked;
            var children = innerBuildTree(hashData, v.id, valueMap, checked)
            var selected = children.filter(v => v.checked == true || v.indeterminate == true).length;
            var indeterminate = (selected > 0 && !checked);
            tree.push({
                id: v.id,
                checked: checked,
                label: v.name,
                data: v,
                visible: true,
                indeterminate: indeterminate,
                children: children
            })
        })
    }
    return tree;
}
//去除空白
export function trim(str) {
    return str.replace(/\s+/g, "");;
}
export function timeStamp(second_time) {
    var time;
    if (parseInt(second_time) > 60) {
        var second = parseInt(second_time) % 60;
        if (second < 10) {
            second = "0" + second + "秒";
        } else {
            second = +second + "秒";
        }
        var min = parseInt(second_time / 60);
        if (min < 10) {
            time = "0" + min + "分" + second;
        } else if (min >= 10 && min <= 60) {
            time = min + "分" + second;
        }
        if (min > 60) {
            min = parseInt(second_time / 60) % 60;
            var hour = parseInt(parseInt(second_time / 60) / 60);
            if (hour < 10) {
                time = "0" + hour + "小时" + min + "分" + second;
            }
            if (hour >= 10 && hour <= 60) {
                time = hour + "小时" + min + "分" + second;
            }
            if (hour > 24) {
                hour = parseInt(parseInt(second_time / 60) / 60) % 24;
                var day = parseInt(parseInt(parseInt(second_time / 60) / 60) / 24);
                time = day + "天" + hour + "小时" + min + "分" + second;
            }
        }
    } else {
        time = parseInt(second_time) + "秒"
    }
    return time;
}
export function formatSeconds(value) {
    var result = '00:00:00';
    var times = parseInt(value)
    var hour, minute, second
    if (times > 0) {
        hour = Math.floor(times / 3600);
        if (hour < 10) {
            hour = "0" + hour;
        }
        minute = Math.floor((times - 3600 * hour) / 60);
        if (minute < 10) {
            minute = "0" + minute;
        }
        second = Math.floor((times - 3600 * hour - 60 * minute) % 60);
        if (second < 10) {
            second = "0" + second;
        }
        result = hour + ':' + minute + ':' + second;
    }
    return result;
}

// 找数组中离某个数最近的数
export function closest(arr, num) {
    var ret = arr[0];
    var distance = Math.abs(ret.times - num);
    for (var i = 1; i < arr.length; i++) {
        var newDistance = Math.abs(arr[i].times - num);
        if (newDistance < distance) {
            distance = newDistance;
            ret = arr[i];
        }
    }
    return ret;
}

//时分秒转换为时间搓

export function countDown(time) {
    var s = 0;
    var hour = time.split('-')[0];
    var min = time.split('-')[1];
    var sec = time.split('-')[2];
    s = Number(hour * 3600) + Number(min * 60) + Number(sec);
    return s * 1000;
}

function formatTen(num) {
    return num > 9 ? (num + "") : ("0" + num);
}
export function formatDate(date) {
    var date = new Date(date)
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = date.getHours();
    var minute = date.getMinutes();
    var second = date.getSeconds();
    return year + "-" + formatTen(month) + "-" + formatTen(day) + " " + formatTen(hour) + ":" + formatTen(minute) + ":" + formatTen(second);
}

export function formatInItDate(data) {
    let s;
    if (data) {
        if (isNaN(data) && !isNaN(Date.parse(data))) {
            s = data;
        } else {
            s = format(data, "YYYY-MM-DD");
        }
    } else {
        s = "";
    }
    return s
}
// 获取当月的所有天数
export function getCountDays(data) {
    var nowday = data.getDate();
    var mowMonth = new Date().getMonth();
    var dayArry = [];
    var curDate = data;
    /* 获取当前月份 */
    var curMonth = curDate.getMonth();
    let x = curMonth + 1
    let month;
    if (x < 10) {
        month = '0' + x
    } else {
        month = String(x)
    }
    /*  生成实际的月份: 由于curMonth会比实际月份小1, 故需加1 */
    curDate.setMonth(curMonth + 1);
    /* 将日期设置为0, 这里为什么要这样设置, 我不知道原因, 这是从网上学来的 */
    curDate.setDate(0);
    /* 返回当月的天数 */
    var count = curDate.getDate();
    for (var k = 1; k <= count; k++) {
        var day;
        if (k < 10) {
            day = month + "-" + '0' + k
        } else {
            day = month + "-" + k
        }
        dayArry.push(day);
    }
    let arr = [];
    if (mowMonth == curMonth) {
        for (var s = 0; s < nowday; s++) {
            arr.push(dayArry[s])
        }
    } else {
        arr = dayArry
    }
    return arr;
}

//获取当月天数
export function GetallDate(year, month) {
    var d = new Date(year, month, 0);
    return d.getDate();
}

// 对象数组去重
export function filterRepeat(arr, prop) {
    return arr.filter(function(element, index, self) {
        return (self.findIndex(el => el[prop] == element[prop]) === index);
    });
}
// 取数组最大值
export function numMaxFn(max, max1) {
    max = max + max1;
    if (max > 0 && max < 500) {
        max = 500;
    } else if (max >= 500 && max < 1000) {
        max = 1000;
    } else if (max >= 1000 && max < 2000) {
        max = 2000;
    } else if (max >= 2000 && max < 3000) {
        max = 3000;
    } else if (max >= 3000 && max < 4000) {
        max = 4000;
    } else if (max >= 4000 && max < 5000) {
        max = 5000;
    } else if (max >= 5000 && max < 6000) {
        max = 6000;
    } else if (max >= 6000 && max < 7000) {
        max = 7000;
    } else if (max >= 7000 && max < 8000) {
        max = 8000;
    } else if (max >= 8000 && max < 9000) {
        max = 9000;
    } else if (max >= 9000 && max < 10000) {
        max = 10000;
    } else if (max >= 10000 && max < 20000) {
        max = 20000;
    }
    return max;
}


export function bubbleSort(arr, type) {
    if (Array.isArray(arr)) {
        for (var i = arr.length - 1; i > 0; i--) {
            for (var j = 0; j < i; j++) {
                if (arr[j][type] < arr[j + 1][type]) {
                    [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
                }
            }
        }
        return arr;
    }
}
export function dropSort(arr, type) {
    if (Array.isArray(arr)) {
        for (var i = arr.length - 1; i > 0; i--) {
            for (var j = 0; j > i; j++) {
                if (arr[j][type] < arr[j + 1][type]) {
                    [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
                }
            }
        }
        return arr;
    }
}

export function getPreMonth(date) {
    var arr = date.split('-');
    var year = arr[0]; //获取当前日期的年份
    var month = arr[1]; //获取当前日期的月份
    var day = arr[2]; //获取当前日期的日
    var days = new Date(year, month, 0);
    days = days.getDate(); //获取当前日期中月的天数
    var year2 = year;
    var month2 = parseInt(month) - 1;
    if (month2 == 0) {
        year2 = parseInt(year2) - 1;
        month2 = 12;
    }
    var day2 = day;
    var days2 = new Date(year2, month2, 0);
    days2 = days2.getDate();
    if (day2 > days2) {
        day2 = days2;
    }
    if (month2 < 10) {
        month2 = '0' + month2;
    }
    var t2 = year2 + '-' + month2 + '-' + day2;
    return t2;
}
export function getNextMonth(date) {
    var arr = date.split('-');
    var year = arr[0]; //获取当前日期的年份
    var month = arr[1]; //获取当前日期的月份
    var day = arr[2]; //获取当前日期的日
    var days = new Date(year, month, 0);
    days = days.getDate(); //获取当前日期中的月的天数
    var year2 = year;
    var month2 = parseInt(month) + 1;
    if (month2 == 13) {
        year2 = parseInt(year2) + 1;
        month2 = 1;
    }
    var day2 = day;
    var days2 = new Date(year2, month2, 0);
    days2 = days2.getDate();
    if (day2 > days2) {
        day2 = days2;
    }
    if (month2 < 10) {
        month2 = '0' + month2;
    }

    var t2 = year2 + '-' + month2 + '-' + day2;
    return t2;
}



export function initYMD(time) {
    let date = new Date(time);
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    if (month < 10) {
        month = "0" + month;
    }
    day = day < 10 ? '0' + day : day;
    return year + "-" + month + "-" + day;
};
export function initY(time) {
    let date = new Date(time);
    let year = date.getFullYear();
    return year;
};
export function initYM(data) {
    let dataObj = new Date(data)
    let y = dataObj.getFullYear() < 10 ? '0' + dataObj.getFullYear() : dataObj.getFullYear();
    let m = dataObj.getMonth() + 1;
    m = m < 10 ? "0" + m : m
    return y + '-' + m
};
export function initMD(data) {
    let dataObj = new Date(data)
    let m = dataObj.getMonth() + 1;
    let day = dataObj.getDate();
    m = m < 10 ? "0" + m : m
    day = day < 10 ? '0' + day : day;
    return m + '-' + day
};
export function initYMDHM(time) {
    let date = new Date(time);
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    if (month < 10) {
        month = "0" + month;
    }
    day = day < 10 ? '0' + day : day;
    let h = date.getHours();
    h = h < 10 ? "0" + h : h;
    let m = date.getMinutes();
    m = m < 10 ? "0" + m : m;
    return year + "-" + month + "-" + day + " " + h + ':' + m;
};
export function initHMS(data) {
    let dataObj = new Date(data);
    let h = dataObj.getHours();
    h = h < 10 ? "0" + h : h;
    let m = dataObj.getMinutes();
    m = m < 10 ? "0" + m : m;
    let s = dataObj.getSeconds();
    s = s < 10 ? "0" + s : s;
    return h + ':' + m + ':' + s
};
export function initHM(data) {
    let dataObj = new Date(data);
    let h = dataObj.getHours();
    h = h < 10 ? "0" + h : h;
    let m = dataObj.getMinutes();
    m = m < 10 ? "0" + m : m;
    let s = dataObj.getSeconds();
    s = s < 10 ? "0" + s : s;
    return h + ':' + m
};

export function initYMDHMS(time) {
    let newDate = new Date(time);
    let yy = newDate.getFullYear();
    let mm = newDate.getMonth() + 1; //获取当前月份(0-11,0代表1月，所以要加1);
    let dd = newDate.getDate(); //获取当前日（1-31）
    let hh = newDate.getHours();
    let minut_M = newDate.getMinutes();
    let ss = newDate.getSeconds();
    mm = mm < 10 ? "0" + mm : mm;
    dd = dd < 10 ? "0" + dd : dd;
    hh = hh < 10 ? "0" + hh : hh;
    minut_M = minut_M < 10 ? "0" + minut_M : minut_M;
    ss = ss < 10 ? "0" + ss : ss;
    return yy + "-" + mm + "-" + dd + ' ' + hh + ':' + minut_M + ':' + ss;
};

export function treeFDSM(data) {
    const map = {};
    const val = [];
    data.forEach((item) => {
        map[item.taskId] = item;
    });
    data.forEach((item) => {
        const parent = map[item.parentId];
        if (parent) {
            (parent.children || (parent.children = [])).push(item);
        } else {
            val.push(item);
        }
    });
    return val;
}

function getDay(num, str) {
    let today = new Date();
    let nowTime = today.getTime();
    let ms = 24 * 3600 * 1000 * num;
    today.setTime(parseInt(nowTime + ms));
    let oYear = today.getFullYear();
    let oMoth = (today.getMonth() + 1).toString();
    if (oMoth.length <= 1) oMoth = '0' + oMoth;
    let oDay = today.getDate().toString();
    if (oDay.length <= 1) oDay = '0' + oDay;
    return oYear + str + oMoth + str + oDay;
}
// 获取当前月的天数
function mGetDate(e) {
    let date = new Date(e) || new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let d = new Date(year, month, 0);
    return d.getDate();
}
// 获取本周的日期
function getWeekDay() {
    let dateString = formatDate(new Date()); //当天的日期，例如2020-2-28
    let presentDate = new Date(dateString);
    let today = presentDate.getDay() !== 0 ? presentDate.getDay() : 7;

    return Array.from(new Array(7), function(val, index) {
        return formatDate(new Date(presentDate.getTime() - (today - index - 1) * 24 * 60 * 60 * 1000));
    });
}
export function getCurrentMonthAndDay(){
    let date = new Date()
    let month = date.getMonth() + 1;
    let day = date.getDate();
    if(month<10){
        month = '0' + month
    }
    if(day<10){
        day = '0' + day
    }
    
    return  month + "月" + day + "日" 
}
// 获取当前月的所有日期
function getNowM(e) {
    let now = new Date();
    let current_month_num = mGetDate();
    let current_month = [];
    for (let i = 1; i <= current_month_num; i++) {
        let day = now.setDate(i);
        let everyDay = formatDate(day);
        current_month.push(everyDay);
    }
    return current_month;
}

//获取两日期之间日期列表函数
export function getdiffdate(stime, etime) {
    //初始化日期列表，数组
    let diffdate = new Array();
    let i = 0;
    //开始日期小于等于结束日期,并循环
    while (stime <= etime) {
        diffdate[i] = stime;
        //获取开始日期时间戳
        let stime_ts = new Date(stime).getTime();
        //增加一天时间戳后的日期
        let next_date = stime_ts + (24 * 60 * 60 * 1000);
        //拼接年月日，这里的月份会返回（0-11），所以要+1
        let next_dates_y = new Date(next_date).getFullYear() + '-';
        let next_dates_m = (new Date(next_date).getMonth() + 1 < 10) ? '0' + (new Date(next_date).getMonth() + 1) + '-' : (new Date(next_date).getMonth() + 1) + '-';
        let next_dates_d = (new Date(next_date).getDate() < 10) ? '0' + new Date(next_date).getDate() : new Date(next_date).getDate();
        stime = next_dates_y + next_dates_m + next_dates_d;
        //增加数组key
        i++;
    }
    return diffdate
}
//获取开始时间到结束时间中间所有日期
export function getDayAll(begin, end) {
    let dateAllArr = new Array();
    let ab = begin.split("-");
    let ae = end.split("-");

    let db = new Date();
    db.setUTCFullYear(ab[0], ab[1] - 1, ab[2]);
    let de = new Date();
    de.setUTCFullYear(ae[0], ae[1] - 1, ae[2]);

    let unixDb = db.getTime();
    let unixDe = de.getTime();
    for (let k = unixDb; k <= unixDe;) {
        dateAllArr.push(initYMD((new Date(k))));
        k = k + 24 * 60 * 60 * 1000;
    }
    return dateAllArr;
}
export function deteleObject(obj) {
    let uniques = [];
    let stringify = {};
    for (let i = 0; i < obj.length; i++) {
        let keys = Object.keys(obj[i]);
        let str = '';
        for (let j = 0; j < keys.length; j++) {
            str += JSON.stringify(keys[j]);
            str += JSON.stringify(obj[i][keys[j]]);
        }
        if (!stringify.hasOwnProperty(str)) {
            uniques.push(obj[i]);
            stringify[str] = true;
        }
    }
    uniques = uniques;
    return uniques;
}

/**
 * 计算两个日期之间的天数
 * @param dateString1  开始日期 yyyy-MM-dd
 * @param dateString2  结束日期 yyyy-MM-dd
 * @returns {number} 如果日期相同 返回一天 开始日期大于结束日期，返回0
 */
function  getDaysBetween(dateString1,dateString2){
    let  startDate = Date.parse(dateString1);
    let  endDate = Date.parse(dateString2);
    if (startDate>endDate){
        return 0;
    }
    if (startDate==endDate){
        return 1;
    }
    let days=(endDate - startDate)/(1*24*60*60*1000);
    return  days;
}
//获取当月的第一天
export function initFirstData() {
    let date = new Date();
    date.setDate(1);
    let month = parseInt(date.getMonth() + 1);
    let day = date.getDate();
    if (month < 10) {
        month = '0' + month
    }
    if (day < 10) {
        day = '0' + day
    }
    return date.getFullYear() + '-' + month + '-' + day
}
//获取当月的最后一天
export function initLastData() {
    let endDate = new Date();
    let currentMonth = endDate.getMonth();
    let nextMonth = ++currentMonth;
    let nextMonthFirstDay = new Date(endDate.getFullYear(), nextMonth, 1);
    let oneDay = 1000 * 60 * 60 * 24;
    let lastTime = new Date(nextMonthFirstDay - oneDay);
    let endMonth = parseInt(lastTime.getMonth() + 1);
    let endDay = lastTime.getDate();
    if (endMonth < 10) {
        endMonth = '0' + endMonth
    }
    if (endDay < 10) {
        endDay = '0' + endDay
    }
    return endDate.getFullYear() + '-' + endMonth + '-' + endDay
}
//获取当月所有日期

// 获取当前月的所有日期
export function getNowM(e) {
    let now = new Date(e) || new Date();
    let current_month_num = mGetDate(e);
    let current_month = [];
    for (let i = 1; i <= current_month_num; i++) {
        let day = now.setDate(i);
        let everyDay = formatDate(day).substring(0, 10);
        current_month.push(everyDay);
    }
    return current_month;
}

//获取开始日期与结束日期之间的所有日期数组
export function getAllDates(begin, end) { //返回 日期的数组 如 ['2020-07-10','2020-07-11']
    var arr = [];
    var ab = begin.split("-");
    var ae = end.split("-");
    var db = new Date();
    db.setUTCFullYear(ab[0], ab[1] - 1, ab[2]);
    var de = new Date();
    de.setUTCFullYear(ae[0], ae[1] - 1, ae[2]);
    var unixDb = db.getTime() - 24 * 60 * 60 * 1000;
    var unixDe = de.getTime() - 24 * 60 * 60 * 1000;
    for (var k = unixDb; k <= unixDe;) {
        k = k + 24 * 60 * 60 * 1000;
        arr.push((new Date(parseInt(k))).FormatS('yyyy-MM-dd'));
    }
    return arr;
}

Date.prototype.FormatS = function(fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
export  function  getDaysBetween(dateString1,dateString2){
    var  startDate = Date.parse(dateString1);
    var  endDate = Date.parse(dateString2);
    var days=(endDate - startDate)/(1*24*60*60*1000);
    // alert(days);
    return  days;
}
/**
 * 获取 blob
 * url 目标文件地址
 */
export function getBlob(url) {
    return new Promise(resolve => {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.responseType = 'blob';
        xhr.onload = () => {
            if (xhr.status === 200) {
                resolve(xhr.response);
            }
        };
        xhr.send();
    });
};

/**
 * 保存 blob
 * filename 想要保存的文件名称
 */
export function saveAs(blob, filename) {
    if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, filename);
    } else {
        const link = document.createElement('a');
        const body = document.querySelector('body');
        link.href = window.URL.createObjectURL(blob);
        link.download = filename;
        // fix Firefox
        link.style.display = 'none';
        body.appendChild(link);
        link.click();
        body.removeChild(link);
        window.URL.revokeObjectURL(link.href);
    }
};

/**
 * 下载
 * @param  {String} url 目标文件地址
 * @param  {String} filename 想要保存的文件名称
 */
export function downloadFileName(url, filename) {
    getBlob(url).then(blob => {
        saveAs(blob, filename);
    });
}
// export  function randomRgbColor() { //随机生成RGB颜色
//     //固定生成浅色系
//     let r = Math.floor(Math.random() * 256); //随机生成256以内r值
//     let g = Math.floor(Math.random() * 256); //随机生成256以内g值
//     let b = Math.floor(Math.random() * 256); //随机生成256以内b值
//     return `rgb(${r},${g},${b})`; //返回rgb(r,g,b)格式颜色
// }
//生成随机颜色
export function randomRgbColor() { //随机生成RGB颜色
    //固定生成浅色系
    // let r = Math.floor(Math.random() * 256); //随机生成256以内r值
    let g = Math.floor(Math.random() * 256); //随机生成256以内g值
    let b = Math.floor(Math.random() * 256); //随机生成256以内b值
    return `rgb(255,${g},${b})`; //返回rgb(r,g,b)格式颜色
}

//获取当天星期几
export function getWeek(){
    let date = new Date();
    let week;
    switch (date.getDay()){
        case 1: week="星期一"; break;
        case 2: week="星期二"; break;
        case 3: week="星期三"; break;
        case 4: week="星期四"; break;
        case 5: week="星期五"; break;
        case 6: week="星期六"; break;
        default: week="星期天";
    }
    return week
};
//根据生日算年龄
export function getAge(arr){
    let birthdays = new Date(arr.replace(/-/g, "/"));
    let d = new Date();
    let age =
        d.getFullYear() -
        birthdays.getFullYear() -
        (d.getMonth() < birthdays.getMonth() ||
        (d.getMonth() == birthdays.getMonth() &&
            d.getDate() < birthdays.getDate())
            ? 1
            : 0);
    return age
};


